using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace TagTool.Devices.Tablet
{
    public class TabletManager : IDeviceManager
    {
        private static IList<ITabletDevice> deviceList;
	
        public TabletManager()
        {
            deviceList = new List<ITabletDevice>();
            uint devices = GetIInfoNumberOfDevices();
            for (uint i = 0; i < devices; i++)
            {
                deviceList.Add(new WinTablet(i));
            }
        }

        #region Properties

        public int NumberOfDevices
        {
            get
            {
                return deviceList.Count;
            }
        }

        #endregion Properties

        #region Methods

        public uint GetIInfoNumberOfDevices()
        {
            uint numberOfDevices = 0;
            WTFunction.WTInfoUInt((uint)WTInfoCategory.Interface, (uint)WTInterface.NDevices, ref numberOfDevices);
            return numberOfDevices;
        }

        public void AddDevice(IDevice tablet)
        {
            if ((tablet != null) && (tablet is ITabletDevice))
            {
                deviceList.Add((ITabletDevice)tablet);
            }
        }

        public void RemoveDevice(IDevice tablet)
        {
            if ((tablet != null) && (tablet is ITabletDevice))
            {
                deviceList.Remove((ITabletDevice)tablet);
            }
        }

        public IDevice GetDevice(int index)
        {
            ITabletDevice device = null;
            if ((index >= 0) && (index < deviceList.Count))
            {
                device = deviceList[index];
            }
            return device;
        }

        public IDevice GetDevice(string name)
        {
            foreach (ITabletDevice device in deviceList)
            {
                if (device.Name.Equals(name))
                {
                    return device;
                }
            }
            return null;
        }

        public static int getDeviceForContext(IntPtr context) {
			foreach (ITabletDevice device in deviceList)
            {
				if (((WinTablet)device).DefaultContextHandle.Equals(context))
                {
                	return device.DeviceId;
                }
			}
			return -1;
        }

        public static ITabletContext getContextForIntPtr(IntPtr context) {
			foreach (ITabletDevice device in deviceList)
            {
				if (((WinTablet)device).DefaultContextHandle.Equals(context))
                {
                	return device.DefaultContext;
                }
			}
			return null;
        }

        #endregion Methods
    }
}
